<template>
  <div class="tab">
    <cube-tab-bar
      :data="tabs"
      :useTransition="false"
      show-slider
      ref="tabBar"
      v-model="selectedLabel"
    ></cube-tab-bar>
    <div class="line"></div>
    <div class="slider-wrapper">
      <cube-slide
        :loop="false"
        :auto-play="false"
        :show-dots="false"
        :initial-index="index"
        ref="slide"
        scroll="onScroll"
        @change="onChange"
        @scroll="onScroll"
        :options="slideOptions"
      >
        <cube-slide-item v-for="(tab, index) in tabs" :key="index">
          <component :is="tab.comps" :data="tab.data" ref="component"></component>
        </cube-slide-item>
      </cube-slide>
    </div>
  </div>
</template>
<script>
export default {
  name: 'tab',
  props: {
    tabs: {
      type: Array,
      default() {
        return []
      }
    },
    initialIndex: { // 默认active位置
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      index: this.initialIndex,
      slideOptions: {
        listenScroll: true,
        probeType: 3,
        directionLockThreshold: 0 // 域值
      }
    }
  },
  mounted() {
    this.onChange(this.index)
  },
  computed: {
    selectedLabel: {
      get() {
        return this.tabs[this.index].label
      },
      set(newVal) {
        this.index = this.tabs.findIndex((value) => {
          return value.label === newVal
        })
      }
    }
  },
  methods: {
    onChange(val) {
      this.index = val
      const component = this.$refs.component[val]
      component.fetch && component.fetch()
    },
    onScroll(obj) {
      // tabar的宽度
      const tabBarWidth = this.$refs.tabBar.$el.clientWidth
      // 全部slider的总宽度
      const sliderWidth = this.$refs.slide.slide.scrollerWidth
      // 按比例位移的宽度
      const transform = -obj.x / sliderWidth * tabBarWidth

      this.$refs.tabBar.setSliderTransform(transform)
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '../../common/stylus/variable.styl'
@import '../../common/stylus/mixin.styl'

.tab
  display flex
  flex-direction column
  height 100%
  & >>> .cube-tab-bar
    font-size $fontsize-medium
    .cube-tab
      padding 13px 0
      color $color-text-s
    .cube-tab_active
      div
        color $color-red
        font-weight 700
    .cube-tab-bar-slider
      background-color $color-red
  .line
    border-1px($color = $color-row-line)
  & >>> .slider-wrapper
    flex 1
    height 0
</style>
